import React, { useEffect, useState } from 'react';
import { Dialog, Form, Input, Select, Switch, Button, MessagePlugin, Textarea, InputNumber } from 'tdesign-react';
import { JupiterCategory, JupiterCategoryForm } from '../../../types/categoryTypes';
import { fetchCategoryTree } from '../../../services/categoryService';

interface CategoryFormProps {
    visible: boolean;
    title: string;
    editingData?: Partial<JupiterCategory>;
    onClose: () => void;
    onSubmit: (data: JupiterCategoryForm) => void;
}

export default function CategoryForm({ visible, title, editingData, onClose, onSubmit }: CategoryFormProps) {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [parentOptions, setParentOptions] = useState<{ label: string; value: string }[]>([]);

    const getParentOptions = async () => {
        try {
            const response = await fetchCategoryTree();
            if (response.code === 200) {
                const options = response.data.map((item: JupiterCategory) => ({
                    label: item.name,
                    value: item.uuid,
                }));
                setParentOptions([{ label: '无父分类', value: '' }, ...options]);
            }
        } catch (error) {
            console.error('获取父分类选项失败:', error);
        }
    };

    useEffect(() => {
        if (visible) {
            getParentOptions();
            if (editingData) {
                form.setFieldsValue({
                    name: editingData.name,
                    description: editingData.description,
                    parentUuid: editingData.parentUuid || '',
                    sortOrder: editingData.sortOrder || 0,
                    isActive: editingData.isActive !== false,
                });
            } else {
                form.reset();
                form.setFieldsValue({
                    sortOrder: 0,
                    isActive: true,
                });
            }
        }
    }, [visible, editingData, form]);

    const handleSubmit = async () => {
        try {
            const result = await form.validate();
            if (result === true) {
                setLoading(true);
                const formData = form.getFieldsValue(true);
                // 处理空字符串的parentUuid
                if (formData.parentUuid === '') {
                    formData.parentUuid = undefined;
                }
                onSubmit(formData as JupiterCategoryForm);
            }
        } catch (error) {
            console.error('表单验证失败:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleCancel = () => {
        form.reset();
        onClose();
    };

    return (
        <Dialog
            header={title}
            visible={visible}
            width={600}
            onClose={handleCancel}
            footer={
                <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
                    <Button theme="default" onClick={handleCancel}>
                        取消
                    </Button>
                    <Button theme="primary" loading={loading} onClick={handleSubmit}>
                        确定
                    </Button>
                </div>
            }
        >
            <Form
                form={form}
                labelWidth={100}
                layout="vertical"
            >
                <Form.FormItem
                    label="分类名称"
                    name="name"
                    rules={[
                        { required: true, message: '请输入分类名称' },
                        { max: 100, message: '分类名称不能超过100个字符' }
                    ]}
                >
                    <Input placeholder="请输入分类名称" />
                </Form.FormItem>

                <Form.FormItem
                    label="父分类"
                    name="parentUuid"
                >
                    <Select
                        placeholder="请选择父分类"
                        options={parentOptions}
                        filterable
                    />
                </Form.FormItem>

                <Form.FormItem
                    label="描述"
                    name="description"
                    rules={[{ max: 500, message: '描述不能超过500个字符' }]}
                >
                    <Textarea
                        placeholder="请输入描述"
                        rows={3}
                    />
                </Form.FormItem>

                <div style={{ display: 'flex', gap: 16 }}>
                    <Form.FormItem
                        label="排序"
                        name="sortOrder"
                        style={{ flex: 1 }}
                    >
                        <InputNumber
                            placeholder="请输入排序值"
                            min={0}
                            max={9999}
                            defaultValue={0}
                        />
                    </Form.FormItem>

                    <Form.FormItem
                        label="是否启用"
                        name="isActive"
                        style={{ width: 100 }}
                    >
                        <Switch />
                    </Form.FormItem>
                </div>
            </Form>
        </Dialog>
    );
}